package com.techwells.learningkites.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.widget.MediaController;
import android.widget.TextView;

import com.techwells.learningkites.R;
import com.techwells.learningkites.networkservice.Constant;
import com.techwells.taco.base.CommonBaseActivity;

public class VideoPlayerActivity extends CommonBaseActivity {
	
	private com.techwells.taco.widget.FullScreenVideoView videoView;	
	private TextView text;
	private Dialog dialog;
	private ProgressDialog progressDialog = null;
	
	private static final int READY_BUFF = 2000 * 1024;
	private static final int CACHE_BUFF = 500 * 1024;
	private String remoteUrl;
	private String localUrl;
	private String videoName;
	private int curPosition = 0;
	private boolean isready = false;
	private boolean iserror = false;
	private int errorCnt = 0;
	private long mediaLength = 0;
	private long readSize = 0;
	
	private final static int VIDEO_STATE_UPDATE = 0;
	private final static int CACHE_VIDEO_READY = 1;
	private final static int CACHE_VIDEO_UPDATE = 2;
	private final static int CACHE_VIDEO_END = 3;

	private final Handler mHandler = new Handler() {
	    @Override
	    public void handleMessage(Message msg) {
	        switch (msg.what) {
	        case VIDEO_STATE_UPDATE:
	            double cachepercent = readSize * 100.00 / mediaLength * 1.0;
	            String s = String.format("已缓存: [%.2f%%]", cachepercent);

	            if (videoView.isPlaying()) {
	                curPosition = videoView.getCurrentPosition();
	                int duration = videoView.getDuration();
	                duration = duration == 0 ? 1 : duration;

	                double playpercent = curPosition * 100.00 / duration * 1.0;

	                int i = curPosition / 1000;
	                int hour = i / (60 * 60);
	                int minute = i / 60 % 60;
	                int second = i % 60;

	                s += String.format(" 播放: %02d:%02d:%02d [%.2f%%]", hour,
	                        minute, second, playpercent);
	            }

//	            tvcache.setText(s);

	            mHandler.sendEmptyMessageDelayed(VIDEO_STATE_UPDATE, 1000);
	            break;

	        case CACHE_VIDEO_READY:
	            isready = true;
	            videoView.setVideoPath(localUrl);
	            videoView.start();
	            break;

	        case CACHE_VIDEO_UPDATE:
	            if (iserror) {
	            	videoView.setVideoPath(localUrl);
	            	videoView.start();
	                iserror = false;
	            }
	            break;

	        case CACHE_VIDEO_END:
	            if (iserror) {
	            	videoView.setVideoPath(localUrl);
	            	videoView.start();
	                iserror = false;
	            }
	            break;
	        }

	        super.handleMessage(msg);
	    }
	};
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_videoview_player);
		initViews();
		playvideo();
	}
	
	private void initViews() {
		videoView = (com.techwells.taco.widget.FullScreenVideoView) findViewById(R.id.videoview);
		
//		Uri uri = Uri.parse(getIntent().getStringExtra("resource"));
//		videoView.setVideoURI(uri);
//		videoView.setVideoPath(getIntent().getStringExtra("resource"));
		
		remoteUrl = getIntent().getStringExtra("resource");
		videoName = getIntent().getStringExtra("name");
		
		videoView.setMediaController(new MediaController(this));
		videoView.requestFocus();
		videoView.setOnPreparedListener(new OnPreparedListener() {

	        public void onPrepared(MediaPlayer mediaplayer) {
	            dismissProgressDialog();
	            videoView.seekTo(curPosition);
	            mediaplayer.start();
	        }
	    });
		videoView.setOnCompletionListener(new OnCompletionListener() {

	        public void onCompletion(MediaPlayer mediaplayer) {
	            curPosition = 0;
	            videoView.pause();
	        }
	    });
		videoView.setOnErrorListener(new OnErrorListener() {

	        public boolean onError(MediaPlayer mediaplayer, int i, int j) {
	            iserror = true;
	            errorCnt++;
	            videoView.pause();
	            showProgressDialog();
	            return true;
	        }
	    });
		
	}

	
	
	private void playvideo() {

	    showProgressDialog();

	    new Thread(new Runnable() {

	        @Override
	        public void run() {
	            FileOutputStream out = null;
	            InputStream is = null;

	            try {
	                URL url = new URL(remoteUrl);
	                HttpURLConnection httpConnection = (HttpURLConnection) url
	                        .openConnection();
	                
	                if(null != Constant.JSESSIONID){
	                	httpConnection.setRequestProperty("Cookie", "JSESSIONID =" + Constant.JSESSIONID);
	                }

	                if (localUrl == null) {
	                    localUrl = Environment.getExternalStorageDirectory()
	                            .getAbsolutePath()
	                            + "/learningkitesCache/"
	                            + System.currentTimeMillis() + ".mp4";
	                }

	                File cacheFile = new File(localUrl);

	                if (!cacheFile.exists()) {
	                    cacheFile.getParentFile().mkdirs();
	                    cacheFile.createNewFile();
	                }

	                readSize = cacheFile.length();
	                out = new FileOutputStream(cacheFile);

	                is = httpConnection.getInputStream();

	                mediaLength = httpConnection.getContentLength();
	                if (mediaLength == -1) {
	                    return;
	                }

	                mediaLength += readSize;

	                byte buf[] = new byte[4 * 1024];
	                int size = 0;
	                long lastReadSize = 0;

	                mHandler.sendEmptyMessage(VIDEO_STATE_UPDATE);

	                while ((size = is.read(buf)) != -1) {
	                    try {
	                        out.write(buf, 0, size);
	                        readSize += size;
	                    } catch (Exception e) {
	                        e.printStackTrace();
	                    }

	                    
	                    if (!isready) {
	                        if ((readSize - lastReadSize) > READY_BUFF) {
	                            lastReadSize = readSize;
	                            mHandler.sendEmptyMessage(CACHE_VIDEO_READY);
	                        }
	                    } else {
	                        if ((readSize - lastReadSize) > CACHE_BUFF
	                                * (errorCnt + 1)) {
	                            lastReadSize = readSize;
	                            mHandler.sendEmptyMessage(CACHE_VIDEO_UPDATE);
	                        }
	                    }
	                }

	                mHandler.sendEmptyMessage(CACHE_VIDEO_END);
	            } catch (Exception e) {
	                e.printStackTrace();
	            } finally {
	                if (out != null) {
	                    try {
	                        out.close();
	                    } catch (IOException e) {
	                        //
	                    }
	                }

	                if (is != null) {
	                    try {
	                        is.close();
	                    } catch (IOException e) {
	                        //
	                    }
	                }
	            }

	        }
	    }).start();
	}
	
	
	private void showProgressDialog() {
	    mHandler.post(new Runnable() {

	        @Override
	        public void run() {
	            if (progressDialog == null) {
	                progressDialog = ProgressDialog.show(VideoPlayerActivity.this,
	                        "视频缓存", "正在努力加载中 ...", true, false);
	            }
	        }
	    });
	}

	private void dismissProgressDialog() {
	    mHandler.post(new Runnable() {

	        @Override
	        public void run() {
	            if (progressDialog != null) {
	                progressDialog.dismiss();
	                progressDialog = null;
	            }
	        }
	    });
	}
	
	
	
}
